import { getDictItemsFromCache, queryDepartTreeList } from '@/api/api'
import Vue from 'vue'
import { UI_CACHE_DB_DICT_DATA } from '@/store/mutation-types'
import isStringEmpty from 'easy-project-vue/dist/utils/isStringEmpty.js'
import findTree from 'easy-project-vue/dist/utils/findTree.js'

// 查询所有部门数据

export const DEPART_TREE = 'DEPART_TREE'

//    列表使用：
//    created() {
//    getDepartTree().finally(() => {
//       this.$forceUpdate()
//     })
//    }
export async function getDepartTree() {
  let res = {}

  // 优先从缓存中读取字典配置
  if (getDictItemsFromCache(DEPART_TREE)) {
    res.result = getDictItemsFromCache(DEPART_TREE)
    res.success = true
    return Promise.resolve(res)
  }

  res = await queryDepartTreeList()

  if (!res.success) {
    return Promise.resolve(res)
  }

  // 存到缓存里
  let codeData = Vue.ls.get(UI_CACHE_DB_DICT_DATA)
  codeData[DEPART_TREE] = res.result
  Vue.ls.set(UI_CACHE_DB_DICT_DATA, codeData, 7 * 24 * 60 * 60 * 1000)
  return Promise.resolve(res)
}

// 表格翻译方法：
// customRender: (text) => {
//   return filterDepartNameById(text)
// }
export function filterDepartNameById(id) {
  if (isStringEmpty(id)) {
    return
  }
  // 优先从缓存中读取字典配置
  if (getDictItemsFromCache(DEPART_TREE)) {
    let tree = getDictItemsFromCache(DEPART_TREE)
    // tree
    let node = findTree(tree, item => item.id === id)
    if (node) {
      return node.title
    }
  }
  return ''
}
